<template>
  <div class="employee-manage">
    <!-- 左侧表格区域 -->
    <div class="left-panel">
      <div class="panel-header">
        <h3>员工管理</h3>
        <div class="header-actions">
          <el-button 
            type="danger" 
            size="small" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleAddEmployee"
          >
            增加用户
          </el-button>
          <el-input
            v-model="searchQuery"
            placeholder="搜索"
            prefix-icon="el-icon-search"
            size="small"
            style="width: 200px;"
            @input="handleSearch"
          />
        </div>
      </div>
      
      <div class="table-container">
        <el-table
          :data="paginatedEmployeeList"
          v-loading="loading"
          style="width: 100%"
          :height="'calc(100vh - 120px)'"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" min-width="80">
            <template slot-scope="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" min-width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" min-width="130">
            <template slot-scope="scope">
              <span>{{ scope.row.phone }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="password" label="密码" min-width="120">
            <template slot-scope="scope">
              <span>{{ '******' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template slot-scope="scope">
              <div style="display: flex; gap: 8px;">
                <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ totalItems }} 条</span>
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next, jumper"
          :total="totalItems"
          background
        >
        </el-pagination>
      </div>
    </div>

    <!-- 增加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form :model="employeeForm" :rules="formRules" ref="employeeForm" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="employeeForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item v-if="isEdit">
          <el-checkbox v-model="changePassword">修改密码</el-checkbox>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit || changePassword">
          <el-input v-model="employeeForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit || changePassword">
          <el-input v-model="employeeForm.confirmPassword" type="password" placeholder="请确认密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EmployeeManage',
  data() {
    return {
      loading: false,
      searchQuery: '',
      selectedRows: [],
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      submitting: false,
      editRow: null,
      changePassword: false, // 控制编辑时是否修改密码
      
      employeeForm: {
        name: '',
        phone: '',
        password: '',
        confirmPassword: ''
      },
      
      formRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { validator: this.validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      
      // 模拟数据
      mockEmployeeList: [
        {
          id: 1,
          name: '张三',
          phone: '13800138001',
          password: '123456',
          createTime: '2024-04-15 10:00:00'
        },
        {
          id: 2,
          name: '李四',
          phone: '13800138002',
          password: '123456',
          createTime: '2024-04-16 14:30:00'
        },
        {
          id: 3,
          name: '王五',
          phone: '13800138003',
          password: '123456',
          createTime: '2024-04-17 09:15:00'
        }
      ]
    }
  },
  computed: {
    filteredEmployeeList() {
      if (!this.searchQuery) {
        return this.mockEmployeeList
      }
      return this.mockEmployeeList.filter(item => 
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
        item.phone.includes(this.searchQuery)
      )
    },
    paginatedEmployeeList() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredEmployeeList.slice(start, end)
    },
    totalItems() {
      return this.filteredEmployeeList.length
    }
  },
  methods: {
    handleSearch() {
      this.currentPage = 1
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
    },
    
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    handleAddEmployee() {
      this.dialogTitle = '增加用户'
      this.isEdit = false
      this.dialogVisible = true
    },
    
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.isEdit = true
      this.editRow = row
      this.employeeForm = {
        name: row.name,
        phone: row.phone,
        password: '',
        confirmPassword: ''
      }
      this.dialogVisible = true
    },
    
    handleDelete(row) {
      this.$confirm(`确定删除用户 "${row.name}" 吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.mockEmployeeList.findIndex(item => item.id === row.id)
        if (index > -1) {
          this.mockEmployeeList.splice(index, 1)
          this.$message.success('删除成功')
        }
      }).catch(() => {})
    },
    
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的用户')
        return
      }
      
      this.$confirm(`确定删除选中的 ${this.selectedRows.length} 个用户吗？`, '批量删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selectedIds = this.selectedRows.map(row => row.id)
        this.mockEmployeeList = this.mockEmployeeList.filter(item => !selectedIds.includes(item.id))
        this.selectedRows = []
        this.$message.success('批量删除成功')
      }).catch(() => {})
    },
    
    validatePassword(rule, value, callback) {
      // 新增用户时密码必填
      if (!this.isEdit) {
        if (!value) {
          callback(new Error('请输入密码'))
          return
        }
        if (value.length < 6 || value.length > 20) {
          callback(new Error('长度在 6 到 20 个字符'))
          return
        }
      }
      // 编辑用户时，如果选择修改密码，则密码必填
      else if (this.changePassword) {
        if (!value) {
          callback(new Error('请输入密码'))
          return
        }
        if (value.length < 6 || value.length > 20) {
          callback(new Error('长度在 6 到 20 个字符'))
          return
        }
      }
      callback()
    },

    validateConfirmPassword(rule, value, callback) {
      // 新增用户时确认密码必填
      if (!this.isEdit) {
        if (!value) {
          callback(new Error('请确认密码'))
          return
        }
        if (value !== this.employeeForm.password) {
          callback(new Error('两次输入密码不一致'))
          return
        }
      }
      // 编辑用户时，如果选择修改密码，则确认密码必填
      else if (this.changePassword) {
        if (!value) {
          callback(new Error('请确认密码'))
          return
        }
        if (value !== this.employeeForm.password) {
          callback(new Error('两次输入密码不一致'))
          return
        }
      }
      callback()
    },
    
    confirmSubmit() {
      this.$refs.employeeForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          
          setTimeout(() => {
            if (this.isEdit) {
              // 编辑用户
              const index = this.mockEmployeeList.findIndex(item => item.id === this.editRow.id)
              if (index > -1) {
                const updateData = {
                  ...this.mockEmployeeList[index],
                  name: this.employeeForm.name,
                  phone: this.employeeForm.phone
                }
                // 如果选择修改密码，则更新密码
                if (this.changePassword) {
                  updateData.password = this.employeeForm.password
                }
                this.mockEmployeeList[index] = updateData
              }
              this.$message.success('编辑成功')
            } else {
              // 新增用户
              const newEmployee = {
                id: Date.now(),
                name: this.employeeForm.name,
                phone: this.employeeForm.phone,
                password: this.employeeForm.password,
                createTime: new Date().toLocaleString('zh-CN')
              }
              this.mockEmployeeList.unshift(newEmployee)
              this.$message.success('添加成功')
            }
            
            this.submitting = false
            this.dialogVisible = false
            this.resetForm()
          }, 1000)
        }
      })
    },
    
    resetForm() {
      this.employeeForm = {
        name: '',
        phone: '',
        password: '',
        confirmPassword: ''
      }
      this.editRow = null
      this.changePassword = false
      if (this.$refs.employeeForm) {
        this.$refs.employeeForm.resetFields()
      }
    }
  }
}
</script>

<style scoped>
.employee-manage {
  height: calc(100vh - 120px);
  padding: 16px;
}

.left-panel {
  width: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-container {
  flex: 1;
  padding: 0 20px;
  overflow: hidden;
  height: calc(100vh - 120px);
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

.table-container .el-table {
  flex: 1 1 auto;
  min-height: 0;
}

.table-container .el-table__body-wrapper {
  max-height: 100%;
  min-height: 200px;
  overflow-y: auto !important;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  border: 1px solid #ebeef5;
}

.el-form-item {
  margin-bottom: 16px;
}
</style>